<?php
namespace App\Model\Backstage;
use App\Model\Account\SystemType;
use App\Model\Base;
use App\Model\Mobile\MobilePlan;
use Illuminate\Support\Facades\DB;
use App\Model\Backstage\Achievement;
use App\Http\Controllers\Backstage\AreaController;
use Qiniu\Storage\BucketManager;
use Qiniu\Storage\UploadManager;
use Qiniu\Auth as qiniuAuth;

/**
 * Class RoomInfo
 * @package App\Model\Backstage
 * 房源信息model
 */
class RoomInfo extends Base
{
    protected $table;
    protected $achievement_model;
    protected $achievement_table;
    protected $customers_table;
    protected $follow_table;
    protected $customer_follow_table;
    protected $source_table;
    protected $room_img_table;
    protected $room_wordbook;//楼盘字典表
    protected $comm_disk = 35;  //公盘对应ID
    protected $private_disk = 36; //私盘对应ID
    protected $excellent_room = 29; //优质房对应ID
    protected $ordinary_room = 28;  //普通房对应ID
    public  function __construct()
    {
        parent::__construct();
        $this->table = 'room_info_'.$this->branch_id;
//        $this->table = 'room_info';

        $this->achievement_model = new Achievement();
//        $this->achievement_table = 'achievement';  //后期需要分公司表
        $this->achievement_table = 'achievement_'.$this->branch_id;


//        $this->customers_table = 'customers'; //后期需要分公司表
        $this->customers_table = 'customers_'.$this->branch_id;


        $this->follow_table = 'follow_'.$this->branch_id;
//        $this->follow_table = 'follow';


        $this->source_table = 'customer_follow_source_'.$this->branch_id;
//        $this->source_table = 'customer_follow_source';


        $this->room_wordbook = 'room_wordbook_'.$this->branch_id;
//        $this->room_wordbook = 'room_wordbook';



        $this->room_img_table = 'room_img_url_'.$this->branch_id;
//        $this->room_img_table = 'room_img_url';

        $this->customer_follow_table = 'customer_follow_'.$this->branch_id;//客源跟进记录表


    }


    /**验证房源重复
     * @param $params
     * @param $rId 房源id  添加验证的时候为0   修改验证的时候有值
     * @return bool
     */
    public function verificationRoomRepeat($params, $rId)
    {
        //DB::raw('from_unixtime(r_entrust_at) as r_entrust_at')
        //DB::raw('from_unixtime(making_room) as making_room')
        $field = [$this->table.'.id', 'property_number','building_id','few_building', 'position', 'room_number', 'floor','total_layer',
            'r_info', 'r_acreage', 'use_type', 'housing_types', 'type_of_house_sale', 'building_s', 'disc_type',  'trading_type',
            'status', 'price',  'unit_price','sale_floor_price', 'rents_type', 'rents', 'rents_unit_price', 'floor_price',
             'taxes_fees', 'some_price', 'r_entrust_at', 'entrust_way', 'admin_cost', 'making_room'
            , 'entrust_number', 'source_type', 'status_quo', 'decoration',
            'support','furniture','appliance', 'rights_type', 'certificate_type', 'payment_type', 'pay_on_type', 'fence_type',
            'industry_type', 'wc_type', 'dorm_type', 'lot_type', 'air_type', 'canteen_type', 'checking_way', 'checking_remark',
            'owner_name', 'owner_phone', 'contact_name', 'contact_phone', 'remark', 'r_d_id','source_uid', 'r_detaile_list',
            'u_username', 'name'
        ];
        $data = DB::table($this->table)
                ->leftjoin('user', 'source_uid', '=', 'u_id')
                ->leftjoin('department', 'r_d_id', '=', 'department.id')
                ->where($this->table.'.id', '<>', $rId)
                ->where('building_id',$params['building_id'])//楼盘字典id
                ->where('few_building',$params['few_building'])//栋座
                ->where('position',$params['position'])//位置
                ->where('room_number',$params['room_number'])//房号
                ->where('room_status', 1)
                ->select($field)
                ->first();
        if (!$data) {
            return false;
        }
        return $data;

    }


    /*
     * 添加房源信息
     * Wu Ning
     */
    public  function addRoomInfo($params)
    {
        //开启事务
        DB::beginTransaction();
        $id = DB::table($this->table)->insertGetId($params);
        //房源编号  =  公司ID + $id    str_pad($anmId, 8,0,STR_PAD_LEFT)
        $propertyNumber = 'FY'.$this->branch_id.str_pad($id, 8,0,STR_PAD_LEFT);
        $updateId = DB::table($this->table)->where('id', $id)->update(['property_number' => $propertyNumber, 'r_updated_at' => time()]);
        if($id && $updateId){
            DB::commit();
            $data = DB::table($this->table)
                ->leftjoin($this->room_wordbook, 'building_id', '=', 'w_id')
                ->where('id', $id)
                ->select('property_number', 'w_name',  'few_building', 'position', 'room_number')
                ->first();
            $log = new Log();
            $log->addlog($params['r_d_id'], $params['source_uid'], 3, '添加房源编号：'.$data->property_number.' 楼盘：'.$data->w_name.' 栋座：'.$data->few_building.' 位置：'.$data->position.' 房号：'.$data->room_number);
            return $id;
        } else {
            DB::rollback();
            return false;
        }
    }

    /*
     * 修改房源
     */
//    public function updataHouse($params)
//    {
//        $params['r_updated_at'] = time();   //修改时间
//        $status = DB::table($this->table)->where('id',$params['id'])->value('status');
//        //如果房源从其他状态改为有效的时候更新委托时间
//        //此处状态值后期需要校验修正97  有效状态ID 97
//        if($status != 97 && $params['status'] == 97){
//            $params['r_entrust_at'] = time();
//        }
//        return DB::table($this->table)
//            ->where('id', $params['id'])
//            ->update($params);
//    }

    /**
     * @param $pageLimit
     * @param array $where
     * @param $keywords
     * @param $appOrPc pc传的是0， app传的是1
     * @return bool
     */
    public function listRoom($pageLimit, $where = [], $keywords, $appOrPc){

        $field = [$this->table.'.id', 'property_number','building_id','few_building', 'position', 'room_number', 'floor','total_layer',
            'r_info', 'r_acreage', 'use_type', 'housing_types', 'type_of_house_sale', 'building_s', 'disc_type',  'trading_type',
            'status', 'price',  'unit_price','sale_floor_price', 'rents_type', 'rents', 'rents_unit_price', 'floor_price',
            'taxes_fees', 'some_price', 'r_entrust_at', 'entrust_way', 'admin_cost',
            'making_room', 'entrust_number', 'source_type', 'status_quo', 'decoration',
            'support','furniture','appliance', 'rights_type', 'certificate_type', 'payment_type', 'pay_on_type', 'fence_type',
            'industry_type', 'wc_type', 'dorm_type', 'lot_type', 'air_type', 'canteen_type', 'checking_way', 'checking_remark',
            'owner_name', 'owner_phone', 'contact_name', 'contact_phone', 'remark', 'r_d_id','source_uid', 'r_detaile_list',
            'u_username', 'name','r_follow_time'
        ];
        if ($appOrPc == 0) {//PC端
            if ($keywords == '' ) {
                $list = DB::table($this->table)
                    ->leftjoin('user', 'source_uid', '=', 'u_id')
                    ->leftjoin('department', 'r_d_id', '=', 'department.id')
                    ->where($where)
                    ->select($field)
                    ->orderBy($this->table.'.id', 'desc')
                    ->paginate($pageLimit);
            }else {
                $list = DB::table($this->table)
                    ->leftjoin('user', 'source_uid', '=', 'u_id')
                    ->leftjoin('department', 'r_d_id', '=', 'department.id')
                    ->where(function ($query) use($where, $keywords){
                        $query->where($where)->where('property_number', 'like', '%'.$keywords.'%');
                    })->orWhere(function ($query) use($where, $keywords) {
                        $query->where($where)->where('owner_name', 'like', '%'.$keywords.'%');
                    })->orWhere(function ($query) use($where, $keywords){
                        $query->where($where)->where('owner_phone', 'like', '%'.$keywords.'%');
                    })->orWhere(function ($query) use($where, $keywords){
                        $query->where($where)->where('room_number', 'like', '%'.$keywords.'%');
                    })
                    ->select($field)
                    ->orderBy($this->table.'.id', 'desc')
                    ->paginate($pageLimit);
            }
        } else {//APP
            if ($keywords == '' ) {
                $list = DB::table($this->table)
                    ->leftjoin('user', 'source_uid', '=', 'u_id')
                    ->leftjoin('department', 'r_d_id', '=', 'department.id')
                    ->where($where)
                    ->select($field)
                    ->orderBy($this->table.'.id', 'desc')
                    ->paginate($pageLimit);
            } else {
                $list = DB::table($this->table)
                    ->leftjoin('user', 'source_uid', '=', 'u_id')
                    ->leftjoin('department', 'r_d_id', '=', 'department.id')
                    ->where(function ($query) use($where, $keywords){
                        $query->where($where)->where('property_number', 'like', '%'.$keywords.'%');
                    })->orWhere(function ($query) use($where, $keywords) {
                        $query->where($where)->where('owner_name', 'like', '%'.$keywords.'%');
                    })->orWhere(function ($query) use($where, $keywords){
                        $query->where($where)->where('owner_phone', 'like', '%'.$keywords.'%');
                    })->orWhere(function ($query) use($where, $keywords){
                        $query->where($where)->where('room_number', 'like', '%'.$keywords.'%');
                    })
                    ->select($field)
                    ->orderBy($this->table.'.id', 'desc')
                    ->paginate($pageLimit);
            }
        }
        if (sizeof($list) == 0) {
            return false;
        }
        return $list;
    }

    /**根据房源的ID 查询该房源的详细信息
     * @param $id
     * @return bool|int
     */
    public function detail($id)
    {
        $field = [$this->table.'.id', 'property_number', 'a_id','building_id','few_building', 'position', 'room_number', 'floor','total_layer',
            'r_info', 'r_acreage', 'use_type', 'housing_types', 'type_of_house_sale', 'building_s', 'disc_type',  'trading_type',
            'status', 'price',  'unit_price','sale_floor_price', 'rents_type', 'rents', 'rents_unit_price', 'floor_price',
            'taxes_fees', 'some_price', DB::raw('from_unixtime(r_entrust_at) as r_entrust_at'), 'entrust_way', 'admin_cost',
            DB::raw('from_unixtime(making_room) as making_room'), 'entrust_number', 'source_type', 'status_quo', 'decoration',
            'support','furniture','appliance', 'rights_type', 'certificate_type', 'payment_type', 'pay_on_type', 'fence_type',
            'industry_type', 'wc_type', 'dorm_type', 'lot_type', 'air_type', 'canteen_type', 'checking_way', 'checking_remark',
            'owner_name', 'owner_phone', 'contact_name', 'contact_phone', 'remark', 'r_d_id','source_uid', 'r_detaile_list',
            'u_username', 'name', 'r_follow_time'
        ];
        return  DB::table($this->table)
            ->leftjoin('user', 'source_uid', '=', 'u_id')
            ->leftjoin('department', 'r_d_id', '=', 'department.id')
            ->where($this->table.'.id', $id)
            ->select($field)
            ->first();
    }

    /*
     *软删除房源
     */
    public function softDelHouse($id)
    {

        $oldStatus = DB::table($this->table)->where('id',$id)->value('room_status');
        DB::beginTransaction();//开启事务
        if($oldStatus == 1){
            $room_status = 2;
            $addFollow = DB::table($this->follow_table)
                ->insertGetId([
                    'f_room_id'       => $id,
                    'f_follow_up_way' => 12,
                    'f_content'    => '正常=>回收站',
                    'f_user_id'    => $this->uid,
                    'f_department_id' => $this->store_id,
                    'f_created_at' => time()
                ]);
        }elseif($oldStatus == 2){
            $room_status = 1;
            $addFollow = DB::table($this->follow_table)
                ->insertGetId([
                    'f_room_id'       => $id,
                    'f_follow_up_way' => 12,
                    'f_content'    => '回收站=>正常',
                    'f_user_id'    => $this->uid,
                    'f_department_id' => $this->store_id,
                    'f_created_at' => time()
                ]);
        }else{
            return -1;
        }

        $updateResult =  DB::table($this->table)->where('id', $id)->update(['room_status' => $room_status, 'r_updated_at' => time()]);

        if ($addFollow && $updateResult) {
            DB::commit();
            return $updateResult;
        } else {
            DB::rollback();
            return false;
        }

    }

    /**
     * @param $id
     * @return mixed
     * 房源回收站列表
     * 房源编号 房源Id 交易 区县 楼盘字典 栋座 位置 房号 业主 委托日 房源归属人 删除时间 删除人部门 删除人
     */
    public function recycleBinList($pageLimit,$where,$keywords){
        //dd($keywords);

        if($keywords == ''){
            $list = DB::table($this->table)
                ->leftjoin('user', 'source_uid', '=', 'u_id')
                ->where('room_status',2)
                ->where($where)
                ->select('property_number','id','trading_type','a_id','building_id','few_building','position','room_number',
                    'owner_name',DB::raw('from_unixtime(r_entrust_at) as r_entrust_at'),'u_username')
                ->orderBy('r_updated_at', 'desc')
                ->paginate($pageLimit);
        }else{
            $list = DB::table($this->table)
                ->leftjoin('user', 'source_uid', '=', 'u_id')
                ->where('room_status',2)
                ->where(function ($query) use($where, $keywords){
                    $query->where('room_status',2)->where('few_building', 'like', '%'.$keywords.'%');//栋座
                })->orWhere(function ($query) use($where, $keywords){
                    $query->where('room_status',2)->where('position', 'like', '%'.$keywords.'%');//位置
                })->orWhere(function ($query) use($where, $keywords){
                    $query->where('room_status',2)->where('room_number', 'like', '%'.$keywords.'%');//房号
                })->orWhere(function ($query) use($where, $keywords){
                    $query->where('room_status',2)->where('owner_name', 'like', '%'.$keywords.'%');//业主
                })->orWhere(function ($query) use($where, $keywords){
                    $query->where('room_status',2)->where('property_number', 'like', '%'.$keywords.'%');//房源编号
                })
                ->select('property_number','id','trading_type','a_id','building_id','few_building','position','room_number',
                    'owner_name',DB::raw('from_unixtime(r_entrust_at) as r_entrust_at'),'u_username')
                ->orderBy('r_updated_at', 'desc')
                ->paginate($pageLimit);
        }
            if (sizeof($list) == 0) {
                return false;
            }

            foreach($list as $key=>$value){
                $value->trading_type = SystemType::getTypeDetail($value->trading_type);
                $value->a_id   = AreaController::getAreaName($value->a_id);
                $roomWordbook = new RoomWordbook();
                $value->building_id = $roomWordbook->getWordbook($value->building_id);
                $delinfo = DB::table($this->follow_table)
                    ->where('f_room_id','=',$value->id)
                    ->leftjoin('user','f_user_id','=','u_id')
                    ->leftjoin('department','f_department_id','=','id')
                    ->select(DB::raw('from_unixtime(f_created_at) as f_created_at'),'name','u_username')
                    ->orderBy('f_id', 'desc')
                    ->first();
                if (sizeof($delinfo) == 0) {
                    $value->deltime = '';
                    $value->deldepartment = '';
                    $value->deluser = '';
                } else {
                    $value->deltime = $delinfo->f_created_at;
                    $value->deldepartment = $delinfo->name;
                    $value->deluser = $delinfo->u_username;
                }

            }
        return $list;
    }

    /*
     * 永久删除房源 和房源跟进 和房源提醒
     *<中介公司 看不到该信息>
     */
    public function DelHouse($id)
    {
        //此处不建议开启事务 因为牵扯录入房源后没有添加跟进或者未添加提醒，
        //所以会导致删除失败，事务回滚



        DB::table($this->follow_table)->where('f_room_id', $id)->delete();
        DB::table($this->source_table)->where(['cfs_type'=>1,'cfs_type_id'=>$id])->delete();
        $data = DB::table($this->table)
            ->leftjoin($this->room_wordbook, 'building_id', '=', 'w_id')
            ->where('id', $id)
            ->select('property_number', 'w_name',  'few_building', 'position', 'room_number')
            ->first();
        $log = new Log();
        $log->addlog($this->store_id, $this->uid, 5, '删除房源编号：'.$data->property_number.' 楼盘：'.$data->w_name.' 栋座：'.$data->few_building.' 位置：'.$data->position.' 房号：'.$data->room_number);

        $auth = new qiniuAuth(env('QINIU_ACCESSKEY'), env('QINIU_SECRETKEY'));
        $uploadMgr = new BucketManager($auth);


        $rid_url = DB::table($this->room_img_table)->where('riu_rid',$id)->select('rid_url')->get();
        $qiniuRel = [];
        foreach($rid_url as $value){
            $fileName = basename($value->rid_url);
            //删除七牛资源操作
            $arr = $uploadMgr->delete('fangchan',$fileName);
            array_push($qiniuRel,$arr);
        }
        DB::table($this->room_img_table)->where('riu_rid',$id)->delete();


        return DB::table($this->table)->where('id', $id)->update(['room_status' => 3, 'r_updated_at' => time()]);

    }

    /**
     * 修改房源状态信息，增加员工业绩计算
     * 房源状态(97有效  98预定  99已售  100已租  101我售  102我租  103暂缓  104未知  105无效)
     * 客源状态（455 有效   456预定  457已购  458已租  459我购  460我租  461暂缓  462未知  463 无效）
     */
    public function saveRoomStatus($param)
    {
        /**
         * 1.房源状态值传过来是  我售 我租的情况下
         * 第一步 根据房源的ID  查询之前的状态是不是本此修改的状态
         * 是的话 不做处理
         * 不是的话  开始业绩分配处理
         *
         * 2.状态值传过来  不是  我售  我租的情况下 只是普通的修改房源信息
         */

        //此处状态值后期需要校验修正
        if($param['status'] == 101 || $param['status'] == 102){  //判断是否为我租或者我售
            $oldStatus = DB::table($this->table)->where('id', $param['id'])->value('status');
            if ($param['status'] != $oldStatus) {
                //这里就需要业绩分配了
                return -1;
            } else {
                //开启事务
                DB::beginTransaction();
                $content =$this->updateRoomAddfoollow($param);
                $addFollow = true;
                if ($content) {
                    $addFollow = DB::table($this->follow_table)->insertGetId([
                        'f_room_id'          => $param['id'],
                        'f_follow_up_way'    => 12,
                        'f_user_id'          => $this->uid,
                        'f_department_id'    => $this->store_id,
                        'f_content'          => $content,
                        'f_created_at'       => time()
                    ]);
                }
                //添加跟进
                $addRoom =  DB::table($this->table)->where('id',$param['id'])->update($param);
                if ($addRoom && $addFollow) {
                    DB::commit();
                    $data = DB::table($this->table)
                        ->leftjoin($this->room_wordbook, 'building_id', '=', 'w_id')
                        ->where('id', $param['id'])
                        ->select('property_number', 'w_name',  'few_building', 'position', 'room_number')
                        ->first();
                    $log = new Log();
                    $log->addlog($param['r_d_id'], $param['source_uid'], 4, '修改房源编号：'.$data->property_number.' 楼盘：'.$data->w_name.' 栋座：'.$data->few_building.' 位置：'.$data->position.' 房号：'.$data->room_number);
                    return true;
                } else {
                    DB::rollback();
                    return false;
                }
            }

        }else{
            //开启事务
            DB::beginTransaction();
            //添加跟进
            $content =$this->updateRoomAddfoollow($param);
            $addFollow = true;
            if ($content) {
                $addFollow = DB::table($this->follow_table)->insertGetId([
                    'f_room_id'          => $param['id'],
                    'f_follow_up_way'    => 12,
                    'f_user_id'          => $this->uid,
                    'f_department_id'    => $this->store_id,
                    'f_content'          => $content,
                    'f_created_at'       => time()
                ]);
            }
            $addRoom =  DB::table($this->table)->where('id',$param['id'])->update($param);
            if ($addRoom && $addFollow) {
                DB::commit();
                $data = DB::table($this->table)
                    ->leftjoin($this->room_wordbook, 'building_id', '=', 'w_id')
                    ->where('id', $param['id'])
                    ->select('property_number', 'w_name',  'few_building', 'position', 'room_number')
                    ->first();
                $log = new Log();
                $log->addlog($param['r_d_id'], $param['source_uid'], 4, '修改房源编号：'.$data->property_number.' 楼盘：'.$data->w_name.' 栋座：'.$data->few_building.' 位置：'.$data->position.' 房号：'.$data->room_number);
                return true;
            } else {
                DB::rollback();
                return false;
            }


        }
    }

    /**
     * 修改房源的信息  添加到跟进里面去
     */
    public function updateRoomAddfoollow($param)
    {
        /**
         * 根据房源ID 查原来 该房源的信息  在跟本次修改的比较   有改动的重要字段 添加到跟进
         * 重要的字段  用途、等级、盘类型、交易、状态、售价、租价、委托时间、业主名字  业主电话
        */
        //楼盘  栋座  位置  房号  面积  委托方式   产权   证件  付款 付佣 看房   部门  员工名
        $str = '';
        $oldData = DB::table($this->table)->where('id', $param['id'])
            ->select('building_id', 'few_building', 'position', 'room_number', 'r_acreage', 'entrust_way', 'rights_type',
            'certificate_type', 'payment_type', 'pay_on_type', 'checking_way', 'r_d_id', 'source_uid',
                'use_type', 'type_of_house_sale', 'disc_type',
                'trading_type', 'status', 'price', 'rents', 'r_entrust_at', 'owner_name', 'owner_phone')
            ->first();

        //楼盘字典
        if ($oldData->building_id != $param['building_id']) {
            $RoomWordBook = new RoomWordbook();
            $str .= '楼盘：'.$RoomWordBook->getWordbook($oldData->building_id).' => '.$RoomWordBook->getWordbook($param['building_id']).' ';
        }
        //栋座
        if ($oldData->few_building != $param['few_building']) {
            $str .= '栋座：'.$oldData->few_building.' => '.$param['few_building'].' ';
        }
        //位置
        if ($oldData->position != $param['position']) {
            $str .= '位置：'.$oldData->position.' => '.$param['position'].' ';
        }
        //房号
        if ($oldData->room_number != $param['room_number']) {
            $str .= '房号：'.$oldData->room_number.' => '.$param['room_number'].' ';
        }
        //面积
        if ($oldData->r_acreage != $param['r_acreage']) {
            $str .= '面积：'.$oldData->r_acreage.' => '.$param['r_acreage'].' ';
        }
        //用途
        if ($oldData->use_type != $param['use_type']) {
            $str .= '用途：'.SystemType::getTypeDetail($oldData->use_type).' => '.SystemType::getTypeDetail($param['use_type']).' ';
        }
        //等级
        if ($oldData->type_of_house_sale != $param['type_of_house_sale']) {
            $str .= '等级：'.SystemType::getTypeDetail($oldData->type_of_house_sale).' => '.SystemType::getTypeDetail($param['type_of_house_sale']).' ';
        }
         //盘类型
        if ($oldData->disc_type != $param['disc_type']) {
            $str .= '盘：'.SystemType::getTypeDetail($oldData->disc_type).' => '.SystemType::getTypeDetail($param['disc_type']).' ';
        }
        //交易
        if ($oldData->trading_type != $param['trading_type']) {
            $str .= '交易：'.SystemType::getTypeDetail($oldData->trading_type).' => '.SystemType::getTypeDetail($param['trading_type']).' ';
        }
        //状态
        if ($oldData->status != $param['status']) {
            $str .= '状态：'.SystemType::getTypeDetail($oldData->status).' => '.SystemType::getTypeDetail($param['status']).' ';
        }
        //售价
        if ($oldData->price != $param['price']) {
            $str .= '售价：'.$oldData->price.' => '.$param['price'].' ';
        }
        //租价
        if ($oldData->rents != $param['rents']) {
            $str .= '租价：'.$oldData->rents.' => '.$param['rents'].' ';
        }
        //委托时间
        if ($oldData->r_entrust_at != $param['r_entrust_at']) {
            $str .= '委托时间：'.date('Y-m-d', $oldData->r_entrust_at).' => '.date('Y-m-d', $param['r_entrust_at']).' ';
        }
        //业主名字
        if ($oldData->owner_name != $param['owner_name']) {
            $str .= '业主姓名：'.$oldData->owner_name.' => '.$param['owner_name'].'  ';
        }
        //业主电话
        if ($oldData->owner_phone != $param['owner_phone']) {
            $str .= '业主电话：'.$oldData->owner_phone.' => '.$param['owner_phone'].' ';
        }
        //委托方式
        if ($oldData->entrust_way != $param['entrust_way']) {
            $str .= '委托方式：'.SystemType::getTypeDetail($oldData->entrust_way).' => '.SystemType::getTypeDetail($param['entrust_way']).' ';
        }
        //产权
        if ($oldData->rights_type != $param['rights_type']) {
            $str .= '产权：'.SystemType::getTypeDetail($oldData->rights_type).' => '.SystemType::getTypeDetail($param['rights_type']).' ';
        }
        //证件
        if ($oldData->certificate_type != $param['certificate_type']) {
            $str .= '证件：'.SystemType::getTypeDetail($oldData->certificate_type).' => '.SystemType::getTypeDetail($param['certificate_type']).' ';
        }
        //付款
        if ($oldData->payment_type != $param['payment_type']) {
            $str .= '付款：'.SystemType::getTypeDetail($oldData->payment_type).' => '.SystemType::getTypeDetail($param['payment_type']).' ';
        }
        //付佣
        if ($oldData->pay_on_type != $param['pay_on_type']) {
            $str .= '付佣：'.SystemType::getTypeDetail($oldData->pay_on_type).' => '.SystemType::getTypeDetail($param['pay_on_type']).' ';
        }
        //看房
        if ($oldData->checking_way != $param['checking_way']) {
            $str .= '看房：'.SystemType::getTypeDetail($oldData->checking_way).' => '.SystemType::getTypeDetail($param['checking_way']).' ';
        }
        //部门
        if ($oldData->r_d_id != $param['r_d_id']) {
            $str .= '部门：'.Department::getDeparName($oldData->r_d_id).' => '.Department::getDeparName($param['r_d_id']).' ';
        }
        //员工
        if ($oldData->source_uid != $param['source_uid']) {
            $str .= '录入人：'.User::getUserNameForId($oldData->source_uid).' => '.User::getUserNameForId($param['source_uid']).' ';
        }
        return $str;
    }

    /**业绩分配
     * @param $r_Info  修改房源的所有信息
     * @param $cId 客源的ID
     * @param $type 单独完成 传1    多人完成 传2
     * @param $money 业绩总提成
     * @param $rate 提成比例字符串
     * @param $a_uid 业绩分成员工ID
     * @param $a_remark 业绩分成备注
     * @return array
     * 房源状态(97有效  98预定  99已售  100已租  101我售  102我租  103暂缓  104未知  105无效)
     * 客源状态（455 有效   456预定  457已购  458已租  459我购  460我租  461暂缓  462未知  463 无效）
     */
    public function performanceDistribution($r_Info, $cId, $type, $money, $rate, $a_uid, $a_remark)
    {
//        dd($cId.'++'.$type.'++'.$money.'++'.$rate.'++'.$a_uid.'++'.$a_remark);
        //开启事务
        DB::beginTransaction();
        /**
         * 房源修改为    我售 101    客源状态就应该修改为    我购 459
         * 房源修改为    我租 102    客源状态就应该修改为    我租 460
         */
        if ($r_Info['status'] == 101) {
            $c_buy_status = 459;
        } elseif ($r_Info['status'] == 102) {
            $c_buy_status = 460;
        } else {
            return -3;//未知错误，请稍后操作
        }

        //修改房源的信息
        $r_Info['r_updated_at'] = time();
        //添加跟进
        $content =$this->updateRoomAddfoollow($r_Info);

        $addFollow = true;
        if ($content) {
            $addFollow = DB::table($this->follow_table)->insertGetId([
                'f_room_id'          => $r_Info['id'],
                'f_follow_up_way'    => 12,
                'f_user_id'          => $this->uid,
                'f_department_id'    => $this->store_id,
                'f_content'          => $content,
                'f_created_at'       => time()
            ]);
        }
        $r_Info['r_follow_time'] = time();//这里要修改跟进时间
        //修改客源的信息
        $c_id = DB::table($this->customers_table)->where('c_id' , $cId)->update(['c_buy_status' => $c_buy_status, 'c_update_at' => time()]);

        if (is_array($r_Info['support'])) {
            $r_Info['support'] = implode(',', $r_Info['support']);
        }
        if (is_array($r_Info['industry_type'])) {
            $r_Info['industry_type'] = implode(',', $r_Info['industry_type']);
        }
        $r_id = DB::table($this->table)->where('id', $r_Info['id'])->update($r_Info);

        //业绩分配处理
        if($type == 1){  //独立完成订单
            $data['a_room_id']       = $r_Info['id'];
            $data['a_customer_id']   = $cId;
            $data['a_uid']           = $a_uid;
            $data['a_money']         = $money;
            $data['a_created_at']    = time();
            $data['a_updated_at']    = time();
            $data['a_remark']        = $a_remark;
        }else{  //多人配合
                $data = [];
                $rate_arr = explode(',' , $rate);
                $user_id = explode(',' , $a_uid);

                if (sizeof($rate_arr) != sizeof($user_id)) {
                    return -1;//人员业绩分配不对等，请仔细检查人员的比例分配
                }
                $rate = array_sum($rate_arr);
                if($rate != 100){
                    return -2;//比例分配错误，所有比例总和只能为100
                }
                foreach($user_id as $k => $v){
                    $data[$k]['a_uid'] = $v;
                    $data[$k]['a_room_id'] = $r_Info['id'];
                    $data[$k]['a_customer_id'] = $cId;
//                    $data[$k]['a_money'] = sprintf("%.2f",substr(sprintf("%.3f", floatval($rate_arr[$k]) / $rate * floatval($money) ), 0, -2));
                    $data[$k]['a_money'] = floatval($rate_arr[$k]) / $rate * floatval($money);
                    $data[$k]['a_created_at'] = time();
                    $data[$k]['a_updated_at'] = time();
                    $data[$k]['a_remark'] = $a_remark;
                }
        }
        //添加业绩分配记录
        $a_id = DB::table($this->achievement_table)->insert($data);
        if ($r_id && $addFollow && $c_id && $a_id) {
            DB::commit();
            //日志操作
            $data = DB::table($this->table)
                ->leftjoin($this->room_wordbook, 'building_id', '=', 'w_id')
                ->where('id', $r_Info['id'])
                ->select('property_number', 'w_name',  'few_building', 'position', 'room_number')
                ->first();
            $cData = DB::table($this->customers_table)
                ->where('c_id', $cId)
                ->select('c_numbering', 'c_user_name')
                ->first();
            $log = new Log();
            $log->addlog($this->store_id, $this->uid, 4, '修改房源编号：'.$data->property_number.' 楼盘：'.$data->w_name.' 栋座：'.$data->few_building.' 位置：'.$data->position.' 房号：'.$data->room_number);
            $log->addlog($this->store_id, $this->uid, 7, '修改客源编号：'.$cData->c_numbering.' 客户：'.$cData->c_user_name);
            return true;
        } else {
            DB::rollback();
            return false;
        }

    }


    /**
     * @param array $map
     * @param $pageLimit
     * @return mixed
     * 获取员工房源录入数量排行
     */
    public function roomAchievementList($where = [], $map = []){

        $user_list = DB::table('user')
                ->leftJoin('department', 'u_d_id', '=', 'id')
                ->where('u_b_id', $this->branch_id)
                ->where($where)
                ->where('u_status', 1)
                ->where('user.is_del', 0)
                ->select('u_id','u_username','name')
                ->get()
                ->toArray();

        $user_list  =  array_map('get_object_vars', $user_list);
        $user_list = $this->remove_duplicate($user_list);

        foreach($user_list as $k => $v){
             $num = DB::table($this->table)->where($map)->where('source_uid', $v['u_id'])->count();
            $user_list[$k]['num'] = $num;
        }
        $list = json_encode($user_list);
        $list = json_decode($list,true);

        array_multisort(array_column($list,'num'),SORT_DESC,$list);
        return $list;
    }

    //二维数组去重
    public 	function remove_duplicate($array){
        $result=array();
        foreach ($array as $key => $value) {
            $has = false;
            foreach($result as $val){
                if($val['u_id']==$value['u_id']){
                    $has = true;
                    break;
                    }
               }
            if(!$has){
                $result[]=$value;
            }

        }
        return $result;
    }

    /**
     * 添加跟进记录时更新房源最后跟进时间
     */
    public function updateFollowTime($id){
        return DB::table($this->table)->where('id', $id)->update(['r_follow_time' => time()]);
    }

    //
    /**
     * @param $param
     * 更新公司自动转移规则对应的房源信息
     * 该方法可作为即时执行调用 参数为单条信息 时间类型输入除过判断外的类型值即可
     */
    public  function updateRuleDisk($param){
        $map = $this->dateMap($param);
        $res =  $this->updateRoomDisk($map, $param, $param['a_move_type']);
        return $res;
    }

    /**
     * @param $param
     * @return array
     * 时间类型判断
     */
    public function dateMap($param){
        $map = [];
        $times = time() - 60 * 60 * 24 * $param['a_day_num'];
        switch($param['a_date_type']){   //判断查找时间类型
            case 0: //最后跟进日期
                $map[] = ['r_follow_time', '<=', $times];
                break;
            case 1: //委托日
                $map[] = ['r_entrust_at', '<=', $times];
                break;
            case 2:  //录入日
                $map[] = ['r_created_at', '<=', $times];
                break;
            default:
                break;
        }
        return $map;
    }

    /**
     * @param $map
     * @param $params
     * @return mixed
     * 更新房屋公私盘 取消优质房
     */
    public function updateRoomDisk($map, $params, $type){

        if(isset($params['a_d_id']) && $params['a_d_id'] != '' && $params['a_d_id'] != 0){  //部门ID
            $map[] = ['r_d_id', $params['a_d_id']];
        }
        //以下所有判断如果类型值为false则代表全部，不作为过滤条件
        if(isset($params['a_trade_type']) && $params['a_trade_type'] != '' && $params['a_trade_type'] != 0){  //交易类型  出租 出售
            $map[] = ['trading_type', $params['a_trade_type']];
        }
        if(isset($params['a_m_status']) && $params['a_m_status'] != '' && $params['a_m_status'] != 0){
            //房源状态 有效  无效 我租等
            $map[] = ['status', $params['a_m_status']];
        }
        if(isset($params['a_use_type']) && $params['a_use_type'] != '' && $params['a_use_type'] != 0){  //房源用途
            $map[] = ['use_type', $params['a_use_type']];
        }
        $update_data = [];
        $str = '';

        if($type == 0){  //修改私盘到公盘
            $map[] = ['disc_type', $this->private_disk];     //查找对应条件所有私盘 私盘不包括 封盘 特盘
            $update_data = [
                'disc_type' => $this->comm_disk,
                'r_updated_at' => time()
            ];
            $str = '私盘到公盘';
        }elseif($type == 2){  //取消优质房
            $map[] = ['type_of_house_sale', $this->excellent_room];    //查询对应条件优质房进行修改
            $update_data = [
                'type_of_house_sale' => $this->ordinary_room,
                'r_updated_at'       => time()
            ];
            $str = '取消优质房';
        }
        //操作日志
        $log = new Log();
        $connect = '手动执行 => '.'超过'.$params['a_day_num'].'天'.$str;
        $log->addlog($this->store_id,$this->uid,13,$connect);
        if(isset($params['a_entrust_way']) && $params['a_entrust_way'] != 0  && $params['a_entrust_way'] != ''){
            $entrust_arr = explode(',', $params['a_entrust_way']);
            return DB::table($this->table)
                ->where($map)
                ->whereIn('entrust_way',$entrust_arr)
                ->update($update_data);
        }else{
           return DB::table($this->table)->where($map)->update($update_data);
        }

    }

    /**
     * @param $param
     * @return mixed
     * 转移房源 或者跟进记录所属人
     * @param $type 1代表更新房源  2代表获取满足条件的房源
     */
    public function moves($param, $type){
        $map = $this->moveMap($param);
        if($type == 1 ){
            if($param['num'] > 0){  //如果转移数量大于0则按条件获取固定数量的数据
                $ids = DB::table($this->table)
                    ->where($map)
                    ->limit($param['num'])
                    ->orderBy('id', 'desc')
                    ->pluck('id');
                return DB::table($this->table)
                    ->whereIn('id',$ids)
                    ->update([
                        'r_d_id' => $param['to_d_id'],
                        'source_uid' => $param['to_uid'],
                        'r_updated_at' => time()
                    ]);
            }else{
                return DB::table($this->table)
                    ->where($map)
                    ->update([
                        'r_d_id' => $param['to_d_id'],
                        'source_uid' => $param['to_uid'],
                        'r_updated_at' => time()
                    ]);
            }

        }else{
            if($param['num'] > 0){  //如果转移数量大于0则按条件获取固定数量的数据
                return DB::table($this->table)
                    ->where($map)
                    ->limit($param['num'])
                    ->orderBy('id', 'desc')
                    ->pluck('id');
            }else{
                return DB::table($this->table)
                    ->where($map)
                    ->orderBy('id', 'desc')
                    ->pluck('id');
            }
        }
    }
    /**
     * @param $param
     * @return array
     * 判断条件
     */
    public function moveMap($param){
        $map[] = ['r_d_id', $param['out_d_id']];  //部门ID
        $map[] = ['source_uid', $param['out_uid']];  //用户ID
        $map[] = ['room_status', 1];

        if(isset($param['w_id']) && $param['w_id'] != ''){  //楼盘字典ID
            $map[] = ['building_id', $param['w_id']];
        }
        if(isset($param['trading_type']) && $param['trading_type'] != ''){ //交易类型 出租 出售 租售
            $map[] = ['trading_type', $param['trading_type']];
        }
        if(isset($param['status']) && $param['status'] != ''){  //房源状态
            $map[] = ['status', $param['status']];
        }
        if(isset($param['start_time']) && $param['start_time'] != ''){ //开始时间
            $map[] = ['r_entrust_at', '>=', strtotime($param['start_time'])];
        }
        if(isset($param['end_time']) && $param['end_time'] != ''){  //结束时间
            $map[] = ['r_entrust_at', '<=', strtotime($param['end_time'])];
        }
        return $map;
    }

    /**
     * @param $params
     * @return mixed
     * 公私盘转移
     */
    public function turns($params){
        $map = $this->dateMap($params); //时间数组
        //部门
        if(isset($params['a_d_id']) && $params['a_d_id'] != ''){
            $map[] = ['r_d_id', $params['a_d_id']];
        }
        //员工
        if(isset($params['a_uid']) && $params['a_uid'] != ''){
            $map[] = ['source_uid', $params['a_uid']];
        }
        //楼盘字典
        if(isset($params['building_id']) && $params['building_id'] != ''){
            $map[] = ['building_id', $params['building_id']];
        }
        //交易类型
        if(isset($params['trading_type']) && $params['trading_type'] != ''){
            $map[] = ['trading_type', $params['trading_type']];
        }
        //状态
        if(isset($params['status']) && $params['status'] != ''){
            $map[] = ['status', $params['status']];
        }
        $updateData = ['r_updated_at' => time()];
        if($params['turn_type'] == 0){   //私转公
            $map[] = ['disc_type', $this->private_disk];
            $updateData = [
                'disc_type' => $this->comm_disk,
                'r_updated_at' => time()
            ];
        } elseif($params['turn_type'] == 1){  //公转私
            $map[] = ['disc_type', $this->comm_disk];
            $updateData = [
                'disc_type' => $this->private_disk,
                'r_updated_at' => time()
            ];
        }
        return DB::table($this->table)
                ->where($map)
                ->update($updateData);
    }

    /**
     * 简单查找房源列表
     */
    public function listRoomFast($pageLimit, $where = [], $keywords){
        $field = ['id', 'property_number', 'entrust_number', 'a_id', 'trading_type', 'building_id', 'few_building', 'room_number',
            'r_acreage', 'status', DB::raw('from_unixtime(r_entrust_at) as r_entrust_at')];
        if ($keywords == '' ) {
            $list = DB::table($this->table)
                ->where($where)
                ->select($field)
                ->orderBy('id', 'desc')
                ->paginate($pageLimit);
        }else {
            $list = DB::table($this->table)
                ->where(function ($query) use($where, $keywords){
                    $query->where($where)->where('property_number', 'like', '%'.$keywords.'%');
                })->orWhere(function ($query) use($where, $keywords) {
                    $query->where($where)->where('owner_name', 'like', '%'.$keywords.'%');
                })->orWhere(function ($query) use($where, $keywords){
                    $query->where($where)->where('owner_phone', 'like', '%'.$keywords.'%');
                })->orWhere(function ($query) use($where, $keywords){
                    $query->where($where)->where('contact_name', 'like', '%'.$keywords.'%');
                })->orWhere(function ($query) use($where, $keywords){
                    $query->where($where)->where('contact_phone', 'like', '%'.$keywords.'%');
                })
                ->select($field)
                ->orderBy('id', 'desc')
                ->paginate($pageLimit);
        }

        if (sizeof($list) == 0) {
            return false;
        }
        return $list;
    }

    /**
     * 根据房源的ID  查询出房源要匹配客源的一些信息
     */
    public function getRoomMatch($id)
    {
        return  DB::table($this->table)->where('id', $id)->select('trading_type', 'price', 'rents', 'r_acreage', 'use_type')->first();
    }

    /**
     *根据房源ID   获取该房源一些重要的字段信息
     */
    public function getImptantInfo($id)
    {
        //93 出售  94 出租  95 租售
        $data = DB::table($this->table)
            ->leftJoin($this->room_wordbook, 'building_id', '=', 'w_id')
            ->leftJoin('system_type as r', 'ri_room_type', '=', 'r.st_id')
            ->leftJoin('system_type as t', 'trading_type', '=', 't.st_id')
            ->leftJoin('system_type as rt', 'rents_type', '=', 'rt.st_id')
            ->leftjoin('department', 'r_d_id', '=', 'department.id')
            ->leftjoin('user', 'source_uid', '=', 'u_id')
            ->where($this->table.'.id', $id)
            ->select('w_name', 'few_building', 'position', 'r.st_name as room_name', 'trading_type', 't.st_name as trad_name',
                'price', 'rents', 'rt.st_name as rents_name', 'owner_name', 'owner_phone', 'remark', 'name', 'u_username',
                'r_entrust_at', 'disc_type', 'source_uid')
            ->first();
        //盘类型(35 公盘     36私盘   37封盘    38下定盘  39斡旋盘)
        //权限判断的时候  根据盘的类型   在根据有没有查看盘的权限  做处理
//        if($this->uid != $data->source_uid && ($data->disc_type == 36 || $data->disc_type == 37 || $data->disc_type == 38 || $data->disc_type == 39)){
//            $data->owner_phone = '';
//        }

        if ($data->trading_type == 94) {
            $res['first'] = '['.$data->w_name.$data->few_building.$data->position.'] '.$data->room_name.$data->trad_name.$data->rents.$data->rents_name;
        } else {
            $res['first'] = '['.$data->w_name.$data->few_building.$data->position.'] '.$data->room_name.'房 '.$data->trad_name.$data->price.'万元';
        }
        $res['secound'] = $data->owner_name.': '.$data->owner_phone;
        if (strlen($data->remark) > 60) {
            $data->remark = mb_substr($data->remark,0,20,'utf-8').'...';
        }
        $res['third'] = $data->remark;
        $res['fouth'] = '【'.$data->name.'】 '.$data->u_username.' ['.date('Y-m-d', $data->r_entrust_at).'委托 ]';
        return $res;
    }


    //快速预览跟进
    public function fastRoomFollow($c_id){
        return DB::table($this->follow_table)
            ->leftJoin('user', 'f_user_id', '=', 'u_id')
            ->where('f_room_id',$c_id)
            ->select('f_id','f_room_id','f_follow_up_way', 'f_content', 'u_username',
                DB::raw('from_unixtime(f_created_at) as f_created_at'))
            ->orderBy('f_id', 'desc')->take(5)->get();
    }

    /**添加 修改 房源信息的时候  验证业主的联系方式有没有重复的
     * @param $phone
     * @param $id
     * @return 有的话返回  房源的编号
     */
    public function verificationPhone($phone, $id)
    {
       return  DB::table($this->table)
            ->where('id', '<>', $id)
            ->where('owner_phone', $phone)
            ->value(DB::raw('GROUP_CONCAT(property_number) as property_number'));
    }

    public function getRoomDetail($id){
        $room = new RoomInfo();
        $detail = $room->detail($id);
        if(!$detail){
            return $this->error(Error::INVALID_ARUGMENT);
        }
        $roomWordbook = new RoomWordbook();
        $detail->building_s = date('Y', $detail->building_s);

        //区县名称
        $detail->a_id_name    = AreaController::getAreaName($detail->a_id);
        $detail->building_name = $roomWordbook->getWordbook($detail->building_id); //楼盘字典
        $detail->use_name    = SystemType::getTypeDetail($detail->use_type);         //用途
        $detail->housing_name = SystemType::getTypeDetail($detail->housing_types);  //房屋类型
        $detail->type_of_house_name = SystemType::getTypeDetail($detail->type_of_house_sale);  //房屋出售类型
        $detail->disc_name = SystemType::getTypeDetail($detail->disc_type);    //盘类型  私盘  公盘
        $detail->trading_name = SystemType::getTypeDetail($detail->trading_type); //交易类型
        $detail->trading_state_name = SystemType::getTypeDetail($detail->status); //交易状态类型
        $detail->rents_name = SystemType::getTypeDetail($detail->rents_type);            //租价类型
        $detail->taxes_fees_name = SystemType::getTypeDetail($detail->taxes_fees);            //包税费类型
        $detail->entrust_name = SystemType::getTypeDetail($detail->entrust_way);    //委托方式
        $detail->source_name = SystemType::getTypeDetail($detail->source_type);    //来源id
        $detail->status_quo_name = SystemType::getTypeDetail($detail->status_quo);    //现状
        $detail->decoration_name = SystemType::getTypeDetail($detail->decoration);    //装修
        $detail->furniture_name = SystemType::getTypeDetail($detail->furniture);    //家具
        $detail->appliance_name = SystemType::getTypeDetail($detail->appliance);    //家电
        $detail->rights_name = SystemType::getTypeDetail($detail->rights_type);    //产权类型
        $detail->certificate_name = SystemType::getTypeDetail($detail->certificate_type);    //证件类型
        $detail->payment_name = SystemType::getTypeDetail($detail->payment_type);    //付款类型
        $detail->pay_on_name = SystemType::getTypeDetail($detail->pay_on_type);    //付拥类型
        $detail->fence_type_name = SystemType::getTypeDetail($detail->fence_type);    //围墙类型
        $detail->wc_name = SystemType::getTypeDetail($detail->wc_type);    //厕所类型
        $detail->dorm_name = SystemType::getTypeDetail($detail->dorm_type);    //宿舍类型
        $detail->lot_name = SystemType::getTypeDetail($detail->lot_type);    //地段类型
        $detail->air_name = SystemType::getTypeDetail($detail->air_type);    //空调类型
        $detail->canteen_name = SystemType::getTypeDetail($detail->canteen_type);    //食堂类型
        $detail->checking_way_name = SystemType::getTypeDetail($detail->checking_way);    //看房方式
        //多选框数据========配套
        $support_name = [];
        if($detail->support){
            $support_arr = explode(',',$detail->support);
            foreach($support_arr as $key => $val){
                $support = SystemType::getTypeDetail($val);    //'配套
                array_push($support_name, $support);
            }
        }
        $detail->support_name = implode(',', $support_name);
        //多选框数据========行业
        $industry_name = [];
        if($detail->industry_type){
            $industry_arr = explode(',',$detail->industry_type);
            foreach($industry_arr as $key => $val){
                $industry = SystemType::getTypeDetail($val);
                array_push($industry_name, $industry);
            }
        }
        $detail->industry_name = implode(',', $industry_name);
        //根据用途变换的输入款  将数据库json字符串转换成数组
        $detail->r_info = json_decode($detail->r_info, true);
        //房源明细列表
        $detail->r_detaile_list = json_decode($detail->r_detaile_list, true);
         return $detail;
    }

    //获取房源提醒
    public function getRoomRemind($id){
      $res =   DB::table($this->source_table)
            ->leftJoin($this->follow_table,'cf_id','f_id')
           ->leftJoin('user','f_user_id','u_id')
           ->leftJoin('department','f_department_id','id')
            ->where('cfs_id',$id)
            ->select('f_id','f_room_id','f_follow_up_way','u_username','name','f_customers_id','f_content',
                DB::raw('from_unixtime(f_created_at) as f_created_at'),'cfs_user_id',DB::raw('from_unixtime(cfs_remind_time) as cfs_remind_time'),
                'cfs_content','cfs_deal_with','cfs_dealwith_pro',
               'cfs_dealwith_time','cfs_manager_review')
            ->first();
        $res->reminded_name = DB::table('user')->where('u_id',$res->cfs_user_id)->value('u_username');
        return $res;

    }

    //通过房源跟进Id 获取跟进与提醒
    public function getRoomFollows($id){
        $list =  DB::table($this->follow_table)
                        ->where('f_id',$id)
                        ->select('f_id','f_room_id','f_follow_up_way','f_user_id','f_department_id','f_customers_id','f_content',
                            DB::raw('from_unixtime(f_created_at) as f_created_at'),
                            'cfs_reminder_range as cfs_user_id','cfs_remind_time','cfs_content','cfs_manager_review')
                        ->first();

            if($list->f_customers_id && $list->f_customers_id != ''){
               $c_numbering = DB::table($this->customers_table)->where('c_id',$list->f_customers_id)->value('c_numbering');
                $c_user_name = DB::table($this->customers_table)->where('c_id',$list->f_customers_id)->value('c_user_name');
                $list->f_customers_id_info = $c_numbering.' '.$c_user_name;
            }

            if (sizeof($list) == 0) {
                return false;
            }
        //【我知道了】逻辑展示
        if($list->cfs_remind_time != null){
            $cfs_deal_with = DB::table($this->source_table)->where('cf_id',$id)
                ->where('cfs_type',1)
                ->where('cfs_user_id',$this->uid)
                ->value('cfs_deal_with');

            if($this->uid == $list->f_user_id && $cfs_deal_with == 1){
                $SourceData = DB::table($this->source_table)
                    ->leftJoin('user','cfs_dealwith_pro','u_id')
                    ->where('cf_id',$id)
                    ->where('cfs_type',1)
                    ->where('cfs_user_id',$this->uid)
                    ->select('cfs_deal_with','u_username','cfs_dealwith_time')
                    ->first();
                $list->cfs_deal_with = $SourceData->cfs_deal_with;
                $list->cfs_dealwith_pro = $SourceData->u_username;
                $list->cfs_dealwith_time = date('Y-m-d H:i:s',$SourceData->cfs_dealwith_time);
            }
        }
            if ($list->cfs_remind_time != 0) {
                $list->cfs_remind_time = date('Y-m-d H:i:s', $list->cfs_remind_time);
            } else {
                $list->cfs_remind_time = '';
            }
        return $list;

    }

    //获取用户名字
    public function getUserName($u_id){
        return DB::table('user')->where('u_id',$u_id)->value('u_username');
    }

    public function addRoomImg($imgArray, $rid)
    {
        $img = [];
        foreach($imgArray as $value) {
            $array = [
                'riu_rid'   =>  $rid,
                'rid_url'   =>  $value,
                'rid_name'  =>  $this->name,
                'rid_time'  =>  date("Y-m-d H:i:s", time())
            ];
            array_push($img, $array);
        }
        return DB::table($this->room_img_table)->insert($img);


    }


    //图片水印
    public function  ImgWatermark($value,$rid,$key,$position){
        $wordSize = env('font_size') ? env('font_size') : 40 ;//水印文字的大小
        $arr = getimagesize($value);
        $width = $arr[0];//图片的宽
        $height = $arr[1];//图片的高
        $bid = $this->branch_id;//公司id
        $bName = DB::table('account_number_manager')->where('anm_id',$bid)->value('anm_branch_name');

        preg_match_all("/[0-9]{1}/",$bName,$arrNum);
        preg_match_all("/[a-zA-Z]{1}/",$bName,$arrAl);
        $newStr = preg_replace('/[^\x{4e00}-\x{9fa5}]/u', '', $bName);  //正则匹配中文
        $chineseNum = mb_strlen($newStr,"utf-8");  //中文数量
        $englishNum = count($arrAl[0]);//英文数量
        $digitalNum = count($arrNum[0]);//数字数量
//        dd('汉字个数:'.$chineseNum.' 英文个数：'.$englishNum.' 数字个数：'.$digitalNum);
        $watermarkwidth = ($chineseNum + $englishNum + $digitalNum)*$wordSize;//水印的宽
//        $watermarkheight = $wordSize;//水印的高
        switch ($position) {
            case 1://left up
                $x = $wordSize;$y = $wordSize+$wordSize;
                break;
            case 2://right up
                $x = $width-$watermarkwidth-$wordSize;$y = $wordSize+$wordSize;
                break;
            case 3://left down
                $x = $wordSize;$y = $height-$wordSize;
                break;
            case 4://right down
                $x = $width-$watermarkwidth-$wordSize;$y = $height-$wordSize;
                break;
            default://centered
                $x = ($width-$watermarkwidth)/2;$y = $height/2-$wordSize;
                break;
        }
        $imgname = md5(uniqid());
        $this_path = $_SERVER['DOCUMENT_ROOT'];
        //水印
        $dst_path = $value->getRealPath();
        //打上文字
//        $font = './fonts/simsun.ttc';//简体路径
//        $font = './fonts/whzbxtkx.ttf';//王汉宗标谐体--空心<有的字不显示>
//        $font = './fonts/fangzheng.ttf';//方正
        $font = './fonts/meishu.ttf';//空心美术
        $dst = imagecreatefromstring(file_get_contents($dst_path));
        $black = imagecolorallocate($dst, 0x00, 0x00, 0x00);//字体颜色
        imagefttext($dst, $wordSize, 0, $x, $y, $black, $font, $bName);
        //输出图片
        list($dst_w, $dst_h, $dst_type) = getimagesize($dst_path);
        $lastName = '';
        switch ($dst_type) {
            case 1://GIF
                $lastName = '.gif';
                imagegif($dst, $this_path.'/uploads/img/'.$bid.$rid.$key.$imgname.$lastName);
                break;
            case 2://JPG
                $lastName = '.jpg';
                imagejpeg($dst, $this_path.'/uploads/img/'.$bid.$rid.$key.$imgname.$lastName);
                break;
            case 3://PNG
                $lastName = '.png';
                 imagepng($dst, $this_path.'/uploads/img/'.$bid.$rid.$key.$imgname.$lastName);
                break;
            default:
                break;
        }
        return $this_path.'/uploads/img/'.$bid.$rid.$key.$imgname.$lastName;
    }

    //图片列表
    public function ImagesLists($Room_id){
        return DB::table($this->room_img_table)->where('riu_rid',$Room_id)->get();
    }

    //删除图片
    public function delImages($riu_id){
        $auth = new qiniuAuth(env('QINIU_ACCESSKEY'), env('QINIU_SECRETKEY'));
        $uploadMgr = new BucketManager($auth);
            foreach($riu_id as $value){
                $rid_url = DB::table($this->room_img_table)->where('riu_id',$value)->value('rid_url');
                $fileName = basename($rid_url);
                //删除七牛资源操作
                $qiniuRel = $uploadMgr->delete('fangchan',$fileName);
                if($qiniuRel === null){
                    DB::table($this->room_img_table)->where('riu_id',$value)->delete();
                }
            }
        return true;
    }

    //业务处理
    public function BusinessProcessing($params){
        $cfs_id             = $params['cfs_id'];//提醒ID
        $type               = $params['type'];//1:房源跟进  2客源跟进
        $id                 = $params['id'];//跟进ID
        $cfs_manager_review = $params['cfs_manager_review'];//经理点评的内容
        //开启事务
        DB::beginTransaction();
        $cfs = DB::table($this->source_table)->where('cfs_id',$cfs_id)->update([
            'cfs_deal_with' => 1,
            'cfs_dealwith_pro'=>$this->uid,//处理人
            'cfs_dealwith_time' => time(),
            'cfs_update_at' => time(),
        ]);
        $fId = true;
        if ($cfs_manager_review) {
            if ($type == 1) {         //有经理点评的话 修改房源跟进
                $fId = DB::table($this->follow_table)->where('f_id', $id)->update(['cfs_manager_review' => $cfs_manager_review, 'f_update_at' => time()]);
            } else if($type == 2) {   //修改客源跟进
                $fId = DB::table($this->customer_follow_table)->where('cf_id', $id)->update(['cfs_manager_review' => $cfs_manager_review, 'cf_update_at' => time()]);
            }
        }
        if ($cfs && $fId){
            DB::commit();
            return true;
        } else {
            DB::rollback();
            return false;
        }




    }

    /**
     * APP处理 和房源列表有关的数据（判断权限）
     */
    public function dealWithData($v, $authories, $uid)
    {
        $roomWordbook = new RoomWordbook();
        $mobilePlan = new MobilePlan();
        $follow = new RoomFollow();
        $v->building_name = $roomWordbook->getWordbook($v->building_id); //楼盘字典
        if (!in_array(51, $authories) && $v->disc_type == 36 && $v->source_uid != $uid) {//私盘
            $v->room_number = '****'; //房号
            $v->owner_name = '***'; //业主姓名
            $v->owner_phone = '***********'; //业主电话
            $v->contact_name = '***'; //联系人姓名
            $v->contact_phone = '***********'; //联系人电话
        }
        if (!in_array(52, $authories) && $v->disc_type == 38 && $v->source_uid != $uid) {//特盘
            $v->room_number = '****'; //房号
            $v->owner_name = '***'; //业主姓名
            $v->owner_phone = '***********'; //业主电话
            $v->contact_name = '***'; //联系人姓名
            $v->contact_phone = '***********'; //联系人电话
        }
        if (!in_array(53, $authories) && $v->disc_type == 39 && $v->source_uid != $uid) {//下定盘
            $v->room_number = '****'; //房号
            $v->owner_name = '***'; //业主姓名
            $v->owner_phone = '***********'; //业主电话
            $v->contact_name = '***'; //联系人姓名
            $v->contact_phone = '***********'; //联系人电话
        }
        if (!in_array(54, $authories) && $v->disc_type == 708 && $v->source_uid != $uid) {//斡旋盘
            $v->room_number = '****'; //房号
            $v->owner_name = '***'; //业主姓名
            $v->owner_phone = '***********'; //业主电话
            $v->contact_name = '***'; //联系人姓名
            $v->contact_phone = '***********'; //联系人电话
        }
        if (!in_array(164, $authories) && $v->disc_type == 37 && $v->source_uid != $uid) {//封盘
            $v->room_number = '****'; //房号
            $v->owner_name = '***'; //业主姓名
            $v->owner_phone = '***********'; //业主电话
            $v->contact_name = '***'; //联系人姓名
            $v->contact_phone = '***********'; //联系人电话
        }
        //如果是公盘   先根据是不是自己的房源做判断 在根据权限做判断 在根据当天有没有写过跟进做判断
        //看业主不必写跟进 162
        $v->lookStatus = 1;//lookStatus == 1不用写跟进   == 2 公盘可能需要写跟进
        if ($v->disc_type == 35 &&  $v->source_uid != $uid && !in_array(162, $authories)) {
            //根据客源ID、员工ID  查询当天该员工有没有对该客源写过跟进
            $res  = $follow->getFollowDay($v->id, $uid);
//                //最后跟进的天  不是今天的话
            if ($res === 2) {
                $v->lookStatus = $res;
                $v->room_number = '****'; //房号
                $v->owner_name = '***'; //业主姓名
                $v->owner_phone = '***********'; //业主电话
                $v->contact_name = '***'; //联系人姓名
                $v->contact_phone = '***********'; //联系人电话;
            }
        }
        $v->r_entrust_at = $v->r_entrust_at != null ? substr($v->r_entrust_at, 0, 10) : '';//委托时间
        $v->making_room = $v->making_room != null ? substr($v->making_room, 0, 10) : '';//交房时间
        $v->building_s = $v->building_s != null ? date('Y',$v->building_s) : '';//建房年代
        $v->r_follow_time = $v->r_follow_time != null ? date('Y-m-d H:i:s',$v->r_follow_time) : '';
        $v->use_name    = SystemType::getTypeDetail($v->use_type);         //用途
        $v->housing_name = SystemType::getTypeDetail($v->housing_types);  //房屋类型
        $v->type_of_house_name = SystemType::getTypeDetail($v->type_of_house_sale);  //房屋出售类型
        $v->disc_name = SystemType::getTypeDetail($v->disc_type);    //盘类型  私盘  公盘
        $v->trading_name = SystemType::getTypeDetail($v->trading_type); //交易类型
        $v->trading_state_name = SystemType::getTypeDetail($v->status); //交易状态类型
        $v->rents_name = SystemType::getTypeDetail($v->rents_type);            //租价类型
        $v->taxes_fees_name = SystemType::getTypeDetail($v->taxes_fees);            //包税费类型
        $v->entrust_name = SystemType::getTypeDetail($v->entrust_way);    //委托方式
        $v->source_name = SystemType::getTypeDetail($v->source_type);    //来源id
        $v->status_quo_name = SystemType::getTypeDetail($v->status_quo);    //现状
        $v->decoration_name = SystemType::getTypeDetail($v->decoration);    //装修
        $v->furniture_name = SystemType::getTypeDetail($v->furniture);    //家具
        $v->appliance_name = SystemType::getTypeDetail($v->appliance);    //家电
        $v->rights_name = SystemType::getTypeDetail($v->rights_type);    //产权类型
        $v->certificate_name = SystemType::getTypeDetail($v->certificate_type);    //证件类型
        $v->payment_name = SystemType::getTypeDetail($v->payment_type);    //付款类型
        $v->pay_on_name = SystemType::getTypeDetail($v->pay_on_type);    //付拥类型
        $v->fence_type_name = SystemType::getTypeDetail($v->fence_type);    //围墙类型
        $v->wc_name = SystemType::getTypeDetail($v->wc_type);    //厕所类型
        $v->dorm_name = SystemType::getTypeDetail($v->dorm_type);    //宿舍类型
        $v->lot_name = SystemType::getTypeDetail($v->lot_type);    //地段类型
        $v->air_name = SystemType::getTypeDetail($v->air_type);    //空调类型
        $v->canteen_name = SystemType::getTypeDetail($v->canteen_type);    //食堂类型
        $v->checking_way_name = SystemType::getTypeDetail($v->checking_way);    //看房方式
        //多选框数据========配套
        $support_name = [];
        if($v->support){
            $support_arr = explode(',',$v->support);
            foreach($support_arr as $key => $val){
                $support = SystemType::getTypeDetail($val);    //'配套
                array_push($support_name, $support);
            }
        }
        $v->support_name = implode(',', $support_name);
        //多选框数据========行业
        $industry_name = [];
        if($v->industry_type){
            $industry_arr = explode(',',$v->industry_type);
            foreach($industry_arr as $key => $val){
                $industry = SystemType::getTypeDetail($val);
                array_push($industry_name, $industry);
            }
        }
        $v->industry_name = implode(',', $industry_name);
        //根据用途变换的输入款  将数据库json字符串转换成数组
        $v->r_info = json_decode($v->r_info, true);
        //房源明细列表
        $v->r_detaile_list = json_decode($v->r_detaile_list, true);
        //查标记
        $hmp_sign_type = $mobilePlan->getSignType(2, $v->id, $uid);
        $v->hmp_sign_type = $hmp_sign_type?$hmp_sign_type:0;
        return $v;
    }

    /**
     * APP 写完公盘的跟进 根据房源的ID  查询该房源的重要信息
     */
    public function getImportantInfo($id)
    {
        return  DB::table($this->table)->where('id', $id)->select('room_number', 'owner_name', 'owner_phone', 'contact_name', 'contact_phone')->first();
    }

    /**
     * APP端  房源图片列表
     */
    public function AppImagesLists($Room_id){
        return  DB::table($this->room_img_table)->where('riu_rid',$Room_id)->select('riu_id' ,'rid_url')->get();

    }
}